<!DOCTYPE html>
<html lang="en" class="app">
<head>
  <meta charset="utf-8" />
  <title>出溜音乐</title>
  <meta name="description" content="app, web app, responsive, admin dashboard, admin, flat, flat ui, ui kit, off screen nav"/>
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" />
  <link rel="stylesheet" type="text/css" href="css/boot.css">
  <link rel="stylesheet" type="text/css" href="css/animate.css" />
  <link rel="stylesheet" type="text/css" href="css/app.css" />
  <link rel="stylesheet" type="text/css" href="css/f.css">
  <link rel="stylesheet" type="text/css" href="css/simple-line-icons.css" />
  <link rel="stylesheet" type="text/css" href="js/jPlayer/jplayer.flat.css" />
  <link rel="stylesheet" type="text/css" href="css/beforeafter-content.css" media="screen" />
  <link rel="stylesheet" type="text/css" href="css/style.css" media="screen" />
  <link rel="stylesheet" type="text/css" href="css/beforeafter-settings.css" media="screen" />
  <script src="down.js"></script>
  <script>window.$ = window.jQuery = require("jquery");</script>
</head>

<body>
  <section class="vbox">
    <header style="width: 100%;height: 30px;line-height: 30px;background-color: #000;text-align: center;">
      <b style="-webkit-app-region: drag;color: #FFF;font-size: 12px;width: 765px;float: left;text-align: left;text-indent: 1em;">出溜音乐</b>
      <img onclick="hideWin()" style="width: 11px;float: right;margin-right: 12px;margin-top: 10px;cursor: pointer;" src="./close.png" />
    </header>
    <section>
      <section class="hbox stretch">
        <section id="content">
          <section class="vbox">
            <section class="w-f-md">
              <section class="hbox stretch bg-black dker">
                <!-- side content -->
                <aside class="col-sm-5 no-padder" id="sidebar">
                  <section class="vbox animated fadeInUp">
                    <section class="scrollable" id="scrollable1" style="width: 50%;left: 0;">
                      <ul class=" list-group list-group-lg radius no-border no-bg m-t-n-xxs m-b-none auto" id="localMusicBox">
                        
                      </ul>
                    </section>
                    <section class="scrollable" id="scrollable2" style="width: 50%;right: 0;">
                      <ul class=" list-group list-group-lg radius no-border no-bg m-t-n-xxs m-b-none auto" id="netMusicBox">
                        
                      </ul>
                    </section>
                  </section>
                </aside>
              </section>
            </section>
            <footer class="footer bg-success dker">
              <div id="jp_container_N">
                <div class="jp-type-playlist">
                  <div id="jplayer_N" class="jp-jplayer hide"></div>
                  <div class="jp-gui">
                    <div class="jp-video-play hide">
                      
                      <a class="jp-video-play-icon">play</a>
                    </div>
                    <div class="jp-interface">
                      <div class="jp-controls">
                        <div onclick="nextMusic()"><a class="jp-previous"><i class="icon-control-rewind i-lg"></i></a></div>
                        <div id="footer-play-icon">
                          <a class="jp-play"><i class="icon-control-play i-2x"></i></a>
                        </div>
                        <div onclick="nextMusic()"><a class="jp-next"><i class="icon-control-forward i-lg"></i></a></div>
                        <div class="jp-progress hidden-xs">
                          <div class="jp-seek-bar dk">
                            <div class="jp-play-bar bg">

                            </div>
                            <div class="jp-title text-lt">
                              <ul>
                                <li id="currentPlayInfo">播放一首歌曲吧</li>
                              </ul>
                            </div>
                          </div>
                        </div>
                        <div class="hidden-xs hidden-sm jp-volume">
                          <div class="jp-volume-bar dk volume-bor">
                            <div class="jp-volume-bar-value lter "></div>
                          </div>
                        </div>
                        <div id="loopBox">
                          <a class="jp-shuffle" title="shuffle"><i class="icon-shuffle text-muted"></i></a>
                        </div>
                      </div>
                    </div>
                  </div>
                  <div class="jp-playlist dropup" id="playlist">
                    <ul class="dropdown-menu aside-xl dker">
                      <!-- The method Playlist.displayPlaylist() uses this unordered list -->
                      <li class="list-group-item"></li>
                    </ul>
                  </div>
                </div>
              </div>
            </footer>
          </section>
        </section>
      </section>
    </section>
  </section>

  <script>
    const { ipcRenderer } = require("electron");
    var fs = require('fs')
    var os = require('os');
    var localMusicPath = `/Applications/chuli_music`
    var filesMusicPath = `/Applications/chuli_files`
    if(os.type() === "Windows_NT"){
      localMusicPath = `C:\\chuliu_yinyue_chuli_music`
      filesMusicPath = `C:\\chuliu_yinyue_chuli_files`
    }

    if(!fs.existsSync(localMusicPath)){
      fs.mkdirSync(localMusicPath)
    }
    if(!fs.existsSync(filesMusicPath)){
      fs.mkdirSync(filesMusicPath)
    }

    function hideWin(){
      ipcRenderer.send("hideWin","close");
    }

    var loopMethod = 1 //随机播放
    let audio = new Audio()
    $(document).ready(function(){
      getLocalList((outIds)=>{
        getMusicList(outIds)
      })
    })
    var netMusics = []
    function getMusicList(outIds){
      $("#netMusicBox").html(``)
      request.get(`https://api.momoman.cn/admin/open/api/music/list?page=1&page_size=100&out_ids=${outIds}`,(err,data,c)=>{
        try{
          data = JSON.parse(c)
          data = data.data
          netMusics = data.list
        }catch(e){
          $("#scrollable1").css('width','100%')
          $("#scrollable2").remove()
          return
        }
        if(err || !data.list){
          $("#scrollable1").css('width','100%')
          $("#scrollable2").remove()
        }
        for (let i=0;i<data.list.length;i++){
          let item = data.list[i]
          $("#netMusicBox").append(`<li class="list-group-item net-music-list">
            <div class="clear text-ellipsis">
              <span>${item.name}</span>
              <span class="text-muted"> - ${item.songer}</span>
            </div>
          </li>`)
        }
      })
    }

    function nextMusic(){
      fs.readdir(localMusicPath, function(err, files){
        let nextMusic = files[Math.floor(Math.random()*files.length)]
        playLocalMusic(nextMusic.split(".")[0])
      })
    }

    function getLocalList(cb){
      let outIds = []
      $("#localMusicBox").html('')
      fs.readdir(localMusicPath, function(err, files){
          for (var i=0; i<files.length; i++){
            let musicInfo = fs.readFileSync(`${localMusicPath}/${files[i]}`)
            musicInfo = JSON.parse(musicInfo)
            outIds.push(musicInfo.id)
            $("#localMusicBox").append(`<li id="x-${musicInfo.id}" mid="${musicInfo.id}" class="list-group-item local-music-list">
                <div class="clear text-ellipsis">
                  <span>${musicInfo.name}</span>
                  <span class="text-muted"> - ${musicInfo.songer}</span>
                </div>
            </li>`)
          }
          if(outIds.length == 0){
            cb('')
            return 
          }
          cb(outIds.join()) 
      });  
    }

    $(document).on("click",".net-music-list",function(){
      if($(this).text().indexOf("下载") != -1){
        return
      }
      let item = netMusics[$(this).index()]
      $(this).text(`正在下载：${item.name} - ${item.songer} - 0%`)
      const Download = new StreamDownload();
      Download.downloadFile(item.url, filesMusicPath,`${item.id}.mp3`, (arg, percentage) => {
        if (arg === "progress"){
            $(this).text(`正在下载：${item.name} - ${item.songer} - ${parseFloat(percentage).toFixed(2)}%`)
            if(percentage >= 100){
              item.url = `${filesMusicPath}/${item.id}.mp3`
              fs.writeFileSync(`${localMusicPath}/${item.id}.json`,JSON.stringify(item))
              getLocalList(()=>{
                $(this).text(`${item.name} - ${item.songer} 下载完成`)
                // $(this).remove()
                if($("#netMusicBox").html() === ""){
                  $("#scrollable1").css('width','100%')
                  $("#scrollable2").remove()
                }
              })
            }
        }
      })
    });

    $("#footer-play-icon").click(function(){
      if(audio.paused){
        $("#footer-play-icon").html(`<a class="jp-pause"><i class="icon-control-pause i-2x"></i></a>`)
        audio.play()
      }else{
        $("#footer-play-icon").html(`<a class="jp-pause"><i class="icon-control-play i-2x"></i></a>`)
        audio.pause()
      }
    })

    function playLocalMusic(mid){
      let curMusicItem = fs.readFileSync(`${localMusicPath}/${mid}.json`)
      curMusicItem = JSON.parse(curMusicItem)
      $(".local-music-list").css('background-color','transparent')
      $(`#x-${mid}`).css('background-color','#000')
      $("#currentPlayInfo").text(`正在播放：${curMusicItem.name} - ${curMusicItem.songer}`)
      $("#footer-play-icon").html(`<a class="jp-pause"><i class="icon-control-pause i-2x"></i></a>`)
      audio.src = curMusicItem.url
      audio.play()
      audio.addEventListener('ended', function () {  
        if(loopMethod == 2){
          playLocalMusic(mid)
        }else{ //单曲循环
          fs.readdir(localMusicPath, function(err, files){
            let nextMusic = files[Math.floor(Math.random()*files.length)]
            playLocalMusic(nextMusic.split(".")[0])
          })
        }
      }, false)
    }

    $(document).on("click",".local-music-list",function(){
      playLocalMusic($(this).attr("mid"))
    });

    $("#loopBox").click(function(){
      if (loopMethod == 1){
        loopMethod = 2
        $("#loopBox").html(`<a class="jp-repeat" title="repeat"><i class="icon-loop text-muted"></i></a>`)
      }else{
        loopMethod = 1
        $("#loopBox").html(`<a class="jp-shuffle" title="shuffle"><i class="icon-shuffle text-muted"></i></a>`)
      }
    })

    
   
    



  </script>
</body>
</html>